/**
 * <p>Copyright (c) 2011 深圳市鹏途信息技术有限公司 </p>
 * <p>				   All right reserved. 		     </p>
 * 
 * <p>项目名称 ： 	东莞交通工程质量监督综合业务系统        </p>
 * <p>创建者   :	ce 
 * 
 * <p>描   述  :   MultiSuccessHandler.java for com.pengtu.security    </p>
 * 
 * <p>最后修改 : $: 2011-7-4-上午11:18:32 v 1.0.0	 ce   $     </p>
 * 
*/

package com.pengtu.security;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.util.StringUtils;

/**
 * 
 * MultiSuccessHandler
 * 
 * 2011-7-4 上午11:18:32
 * 
 * @version 1.0.0
 * 
 */
public class MultiUrlLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler  {
		protected final Log logger = LogFactory.getLog(this.getClass());
	    private boolean useReferer = false;

	    protected MultiUrlLogoutSuccessHandler() {
	    	
	    }
	    
	    /**
	     * Builds the target URL according to the logic defined in the main class Javadoc.
	     */
	    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
	    	String defaultTargetUrl = SpringSecurityUtils.determineLogoutUrlToUseForThisRequest(request, response);
	        if (isAlwaysUseDefaultTargetUrl()) {
	            return defaultTargetUrl;
	        }
	        // Check for the parameter and use that if available
	        String targetUrl = request.getParameter(this.getTargetUrlParameter());

	        if (StringUtils.hasText(targetUrl)) {
	            try {
	                targetUrl = URLDecoder.decode(targetUrl, "UTF-8");
	            } catch (UnsupportedEncodingException e) {
	                throw new IllegalStateException("UTF-8 not supported. Shouldn't be possible");
	            }
	            logger.debug("Found targetUrlParameter in request: " + targetUrl);
	            return targetUrl;
	        }

	        if (useReferer && !StringUtils.hasLength(targetUrl)) {
	            targetUrl = request.getHeader("Referer");
	            logger.debug("Using Referer header: " + targetUrl);
	        }

	        if (!StringUtils.hasText(targetUrl)) {
	            targetUrl = defaultTargetUrl;
	            logger.debug("Using default Url: " + targetUrl);
	        }

	        return targetUrl;
	    }
	    


}
